package info.leetcode.answer.Link.moveOrInsert;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 删除排序链表中的重复元素2
 * @date 2024/3/19 14:42
 */
public class DeleteDuplicates2 {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static ListNode repeatVal = null;


    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null ||head.next == null) {
            return head;
        }
        ListNode next = deleteDuplicates(head.next);
        if (repeatVal != null) {
            if (head.val == repeatVal.val) {
                return next;
            }
            if (next == null){
                head.next = next ;
                return head ;
            }
            if (next.val == repeatVal.val) {
                return next.next;
            }
        }
        if (head.val == next.val) {
            repeatVal = next;
            return next;
        }
        head.next = next;
        return head;
    }

    public static ListNode getList(int[] nums) {
        ListNode head = new ListNode();
        ListNode temp = null;
        for (int i = 0; i < nums.length; i++) {
            if (temp == null) {
                temp = head;
                head.val = nums[i];
            } else {
                ListNode listNode = new ListNode();
                listNode.val = nums[i];
                temp.next = listNode;
                temp = listNode;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode list = getList(new int[]{1, 2,2});
        ListNode listNode = deleteDuplicates(list);
        System.out.println(listNode);
    }
}
